package com.etlmaster.executor.utils;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.vfs2.FileObject;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;

import com.etlmaster.executor.utils.DpExecutorUtils;
import com.etlmaster.jdbc.JdbcTemplate;
import com.etlmaster.util.vfs.VfsServer;
import com.etlmaster.util.vfs.VfsUtils;


/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class DpVfsUtils {
	
	VfsUtils vfsUtils = VfsUtils.getInstance();
	
	private static DpVfsUtils instance = new DpVfsUtils();

	public static DpVfsUtils getInstance(){
		return instance;
	}
	
	private DpVfsUtils(){
	}
	
	public FileObject resolveFile(String absFilePath) {
		absFilePath = mappEscapePath(absFilePath);
		return vfsUtils.resolveFile(absFilePath);
	}
	
	public void closeFileObject(FileObject fileObject){
		vfsUtils.closeFileObject(fileObject);
	}
	
	private SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
	
	public String mappEscapePath(String escapePath){//接口机转义替换
		if(escapePath!=null && escapePath.length()>0 && escapePath.matches(".*\\$\\{.*\\}.*")){//本地文件系统
			return DpExecutorUtils.variableSubstitution(escapePath, buildEscapeData());
		}else{
			return escapePath;
		}
	}
	
	public Map<String,Object> buildEscapeData(){
		Map<String,VfsServer> ftps = fetchVfsServer();
		Map<String,Object> data = new HashMap<String,Object>();
		for (Iterator iterator = ftps.entrySet().iterator(); iterator.hasNext();) {
			Map.Entry<String,VfsServer> entry = (Map.Entry<String,VfsServer>) iterator.next();
			data.put(entry.getKey(), entry.getValue().toString());
		}
		data.put("current_date", sdf.format(System.currentTimeMillis()));
		return data;
	}
	
	@SuppressWarnings("unchecked")
	public Map<String,VfsServer> fetchVfsServer(JdbcTemplate jdbcTemplate){
		return (Map<String,VfsServer>)jdbcTemplate.query("select * from data_trans_ftpserv",new ResultSetExtractor(){
			public Map<String,VfsServer> extractData(ResultSet rs) throws SQLException,DataAccessException {
				Map<String,VfsServer> result = new HashMap<String,VfsServer>();
				while(rs.next()){
					String servName = rs.getString("servname");
					String host = rs.getString("ip");
					String port = rs.getString("port");
					String user = rs.getString("username");
					String pwd = rs.getString("password");
					String scheme = rs.getString("ftptype");
					result.put(servName, new VfsServer(scheme, host, port, user, pwd ));
				}
				return result;
			}
		});
	}
	
	public Map<String,VfsServer> fetchVfsServer(){
		return fetchVfsServer(new JdbcTemplate());
	}
	
	
	
}
